import tkinter as tk
from tkinter import filedialog, messagebox, ttk, scrolledtext
import threading
import os
import sys
import time
import traceback

# 添加当前目录到系统路径
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.append(current_dir)
sys.path.append(parent_dir)

try:
    from walmart_api import WalmartAPI
    from walmartbatch_upload import upload_products_from_csv
except ImportError as e:
    print(f"导入模块失败: {e}")
    traceback.print_exc()

class WalmartUploaderApp:
    def __init__(self, root):
        self.root = root
        self.root.title("沃尔玛产品上传工具")
        self.root.geometry("700x600")
        
        # 创建框架
        self.frame = ttk.Frame(root, padding="10")
        self.frame.pack(fill=tk.BOTH, expand=True)
        
        # 认证信息
        ttk.Label(self.frame, text="Client ID:").grid(column=0, row=0, sticky=tk.W, pady=5)
        self.client_id_var = tk.StringVar()
        ttk.Entry(self.frame, width=50, textvariable=self.client_id_var).grid(column=1, row=0, pady=5, columnspan=2)
        
        ttk.Label(self.frame, text="Client Secret:").grid(column=0, row=1, sticky=tk.W, pady=5)
        self.client_secret_var = tk.StringVar()
        ttk.Entry(self.frame, width=50, textvariable=self.client_secret_var, show="*").grid(column=1, row=1, pady=5, columnspan=2)
        
        # 显示/隐藏密钥按钮
        self.show_secret = tk.BooleanVar(value=False)
        ttk.Checkbutton(self.frame, text="显示密钥", variable=self.show_secret, command=self.toggle_secret_visibility).grid(column=3, row=1, pady=5)
        
        # API环境选择
        ttk.Label(self.frame, text="API环境:").grid(column=0, row=2, sticky=tk.W, pady=5)
        self.api_env = tk.StringVar(value="生产环境")
        env_combobox = ttk.Combobox(self.frame, textvariable=self.api_env, values=["生产环境", "测试环境"])
        env_combobox.grid(column=1, row=2, sticky=tk.W, pady=5)
        env_combobox.configure(state="readonly")

        # CSV文件选择
        ttk.Label(self.frame, text="CSV文件:").grid(column=0, row=3, sticky=tk.W, pady=5)
        self.csv_path_var = tk.StringVar()
        ttk.Entry(self.frame, width=50, textvariable=self.csv_path_var).grid(column=1, row=3, pady=5, columnspan=2)
        ttk.Button(self.frame, text="浏览...", command=self.browse_csv).grid(column=3, row=3, pady=5)
        
        # 添加新建CSV模板按钮
        ttk.Button(self.frame, text="创建CSV模板", command=self.create_csv_template).grid(column=1, row=4, pady=5)
        
        # 按钮框架
        button_frame = ttk.Frame(self.frame)
        button_frame.grid(column=0, row=5, columnspan=4, pady=10)
        
        # 测试连接按钮
        ttk.Button(button_frame, text="测试API连接", command=self.test_connection).grid(column=0, row=0, padx=10)
        
        # 上传按钮
        ttk.Button(button_frame, text="上传产品", command=self.start_upload).grid(column=1, row=0, padx=10)
        
        # 清空日志按钮
        ttk.Button(button_frame, text="清空日志", command=self.clear_log).grid(column=2, row=0, padx=10)
        
        # 状态显示
        self.status_var = tk.StringVar(value="准备就绪")
        status_frame = ttk.Frame(self.frame, relief=tk.SUNKEN, borderwidth=1)
        status_frame.grid(column=0, row=6, columnspan=4, pady=5, sticky=tk.EW)
        ttk.Label(status_frame, textvariable=self.status_var, padding=3).pack(side=tk.LEFT)
        
        # 进度条
        self.progress = ttk.Progressbar(self.frame, orient=tk.HORIZONTAL, length=600, mode='indeterminate')
        self.progress.grid(column=0, row=7, columnspan=4, pady=5, sticky=tk.EW)
        
        # 日志显示 - 使用scrolledtext替代Text和Scrollbar
        ttk.Label(self.frame, text="日志:").grid(column=0, row=8, sticky=tk.W, pady=5)
        self.log_text = scrolledtext.ScrolledText(self.frame, width=80, height=15, wrap=tk.WORD)
        self.log_text.grid(column=0, row=9, columnspan=4, pady=5, sticky=tk.NSEW)
        
        # 设置行列权重以允许调整大小
        self.frame.columnconfigure(1, weight=1)
        self.frame.rowconfigure(9, weight=1)
        
        # 初始化日志
        self.log("沃尔玛产品上传工具已启动")
        self.log("请输入您的API凭证并选择要上传的CSV文件")
        
    def toggle_secret_visibility(self):
        """切换Client Secret显示/隐藏状态"""
        entry_widget = self.frame.grid_slaves(row=1, column=1)[0]
        if self.show_secret.get():
            entry_widget.config(show="")
        else:
            entry_widget.config(show="*")
        
    def browse_csv(self):
        """浏览并选择CSV文件"""
        filename = filedialog.askopenfilename(filetypes=[("CSV文件", "*.csv")])
        if filename:
            self.csv_path_var.set(filename)
            self.log(f"已选择CSV文件: {filename}")
    
    def create_csv_template(self):
        """创建CSV模板文件"""
        filename = filedialog.asksaveasfilename(
            defaultextension=".csv",
            filetypes=[("CSV文件", "*.csv")],
            initialfile="walmart_products_template.csv"
        )
        if filename:
            # 获取模板文件路径
            template_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'products_template.csv')
            
            try:
                # 复制模板文件
                with open(template_path, 'r', encoding='utf-8') as source:
                    content = source.read()
                
                with open(filename, 'w', encoding='utf-8', newline='') as target:
                    target.write(content)
                
                self.log(f"模板文件已创建: {filename}")
                messagebox.showinfo("成功", f"模板文件已创建: {filename}")
            except Exception as e:
                error_msg = f"创建模板文件失败: {e}"
                self.log(error_msg)
                self.log(traceback.format_exc())
                messagebox.showerror("错误", error_msg)
    
    def log(self, message):
        """添加日志消息到日志框"""
        # 获取当前时间
        timestamp = time.strftime("%H:%M:%S", time.localtime())
        formatted_message = f"[{timestamp}] {message}"
        
        # 添加消息到日志框
        self.log_text.insert(tk.END, f"{formatted_message}\n")
        self.log_text.see(tk.END)  # 自动滚动到最新消息
        
        # 打印到控制台
        print(formatted_message)
    
    def clear_log(self):
        """清空日志"""
        self.log_text.delete(1.0, tk.END)
        self.log("日志已清空")
    
    def test_connection(self):
        """测试API连接"""
        client_id = self.client_id_var.get().strip()
        client_secret = self.client_secret_var.get().strip()
        
        if not client_id or not client_secret:
            messagebox.showerror("错误", "请输入Client ID和Client Secret")
            return
        
        # 开始进度条
        self.progress.start()
        self.status_var.set("正在测试连接...")
        
        # 在后台线程中执行测试
        threading.Thread(target=self.test_connection_task, args=(client_id, client_secret)).start()
    
    def test_connection_task(self, client_id, client_secret):
        """测试API连接的后台任务"""
        try:
            # 创建API客户端
            self.log(f"正在使用Client ID: {client_id[:8]}...测试API连接")
            walmart_api = WalmartAPI(client_id, client_secret)
            
            # 测试认证和API连接
            self.log("正在验证认证信息并测试API连接...")
            success, message = walmart_api.test_api_connection()
            
            if success:
                self.log(f"连接测试成功: {message}")
                self.status_var.set("连接测试成功！")
                messagebox.showinfo("成功", "连接测试成功！API认证和连接有效。")
            else:
                error_msg = f"连接测试失败: {message}"
                self.log(error_msg)
                self.status_var.set("连接测试失败")
                messagebox.showerror("错误", error_msg)
                
        except Exception as e:
            error_msg = f"连接测试失败: {str(e)}"
            self.log(error_msg)
            self.log(traceback.format_exc())
            self.status_var.set("连接测试失败")
            messagebox.showerror("错误", error_msg)
        finally:
            # 停止进度条
            self.progress.stop()
    
    def start_upload(self):
        """开始上传产品"""
        client_id = self.client_id_var.get().strip()
        client_secret = self.client_secret_var.get().strip()
        csv_path = self.csv_path_var.get().strip()
        
        if not client_id or not client_secret:
            messagebox.showerror("错误", "请输入Client ID和Client Secret")
            return
            
        if not csv_path:
            messagebox.showerror("错误", "请选择CSV文件")
            return
            
        if not os.path.exists(csv_path):
            messagebox.showerror("错误", f"CSV文件不存在: {csv_path}")
            return
        
        # 先进行连接测试
        self.log("上传前先测试API连接...")
        self.status_var.set("正在验证API连接...")
        self.progress.start()
        
        # 创建临时API客户端测试连接
        try:
            walmart_api = WalmartAPI(client_id, client_secret)
            success, message = walmart_api.test_api_connection()
            
            if not success:
                self.log(f"API连接测试失败: {message}")
                self.status_var.set("API连接失败")
                self.progress.stop()
                messagebox.showerror("错误", f"API连接测试失败，无法上传产品: {message}")
                return
                
            self.log("API连接测试成功，开始上传产品...")
            
        except Exception as e:
            self.log(f"API连接测试异常: {e}")
            self.log(traceback.format_exc())
            self.status_var.set("API连接失败")
            self.progress.stop()
            messagebox.showerror("错误", f"API连接异常，无法上传产品: {str(e)}")
            return
        
        # 开始上传
        self.status_var.set("正在上传...")
        
        # 在后台线程中执行上传
        threading.Thread(target=self.upload_task, args=(client_id, client_secret, csv_path)).start()
    
    def upload_task(self, client_id, client_secret, csv_path):
        """上传产品的后台任务"""
        try:
            # 开始上传
            self.log(f"开始从{csv_path}上传产品...")
            
            # 使用之前定义的函数进行上传
            result = upload_products_from_csv(client_id, client_secret, csv_path)
            
            if result:
                feed_id = result.get('feedId')
                success_msg = f"上传任务已提交，任务ID: {feed_id}"
                self.log(success_msg)
                
                # 更新状态
                self.status_var.set("上传完成！")
                messagebox.showinfo("成功", success_msg)
            else:
                error_msg = "上传失败，请查看日志了解详情"
                self.log(error_msg)
                self.status_var.set("上传失败")
                messagebox.showerror("失败", error_msg)
        except Exception as e:
            error_msg = f"上传过程中出现错误: {str(e)}"
            self.log(error_msg)
            self.log(traceback.format_exc())
            self.status_var.set("上传失败")
            messagebox.showerror("错误", error_msg)
        finally:
            # 停止进度条
            self.progress.stop()

# 启动GUI应用
if __name__ == "__main__":
    root = tk.Tk()
    app = WalmartUploaderApp(root)
    root.mainloop() 